#!/usr/bin/env python3
# _*_coding:utf-8 _*_
__author__ = "Gao"
from rest_framework.permissions import BasePermission
from django.contrib.auth.models import AnonymousUser
from django.conf import settings


class IsAuthenticated(BasePermission):
    """
    Allows access only to authenticated users.
    """

    def has_permission(self, request, view):
        if request.method == 'OPTIONS':    # OPTIONS请求一律放行
            return True

        if isinstance(request.user,AnonymousUser):    # 没有提供Token的是匿名用户
            return False
        try:
            return request.user and request.user.get('is_authed')    # 如果request中有user变量，并且已授权,表示通过了Token验证
        except Exception:
            return False
        # return False


class IsSelf(BasePermission):
    """修改用户信息必须是登录账户自己"""

    def has_object_permission(self, request, view, obj):
        # 'GET', 'HEAD', 'OPTIONS'方法一直被允许
        if obj['id'] == request.user['id']:
            return True    # 判断是否是article的所有者
        return False


class IsAdminOnly(BasePermission):
    """只有管理员有权限"""
    def has_permission(self, request, view):
        if request.method == 'OPTIONS':    # OPTIONS请求一律放行
            return True

        if isinstance(request.user,AnonymousUser):    # 没有提供Token的是匿名用户
            return False
        try:
            return request.user and request.user.get('is_admin')    # 判断是否是admin
        except Exception:
            return False